# -*- coding:utf-8 -*-
"""
@Time : 2020-12-15 11:54
@Author: langengel
@Des: 数据库初始化
"""

import logging

from fastapi import FastAPI, Request
from starlette.responses import JSONResponse
from tortoise import Tortoise
from tortoise.exceptions import DoesNotExist, IntegrityError

from config.database import DB_ORM_CONFIG

logger = logging.getLogger("uvicorn")

# generate_schemas
generate_schemas = True


async def init_mysql(app: FastAPI):
    logger.info("init mysql ...")

    @app.on_event("startup")
    async def init_orm() -> None:  # pylint: disable=W0612
        await Tortoise.init(
            config=DB_ORM_CONFIG,
        )
        # logger.info("Tortoise-ORM started, %s, %s", Tortoise._connections, Tortoise.apps)
        for apps in Tortoise.apps:
            table = ''
            for model in Tortoise.apps[apps]:
                table += ' ' + model
            logger.info("Tortoise-ORM started table, %s, %s", apps, table)

        if generate_schemas:
            logger.info("Tortoise-ORM generating schema")
            await Tortoise.generate_schemas()
            logger.info("Tortoise-ORM generating schema ok...")

    @app.on_event("shutdown")
    async def close_orm() -> None:  # pylint: disable=W0612
        await Tortoise.close_connections()
        logger.info("Tortoise-ORM shutdown")

    @app.exception_handler(DoesNotExist)
    async def does_not_exist_exception_handler(req: Request, exc: DoesNotExist):

        return JSONResponse(status_code=404, content={"detail": "查询对象不存在"})

    @app.exception_handler(IntegrityError)
    async def integrity_error_exception_handler(req: Request, exc: IntegrityError):
        return JSONResponse(
            status_code=422,
            content={"detail": f"{exc}"},
        )
